package cn.lcsjsxy.yxc.servlet;

import jakarta.servlet.ServletConfig;
import jakarta.servlet.ServletContext;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebInitParam;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.util.Enumeration;

@WebServlet(
        urlPatterns = "/ServletTestTwo",
        initParams = {@WebInitParam(name = "key2a",value = "value2a"),@WebInitParam(name = "key2b",value = "key2b")}
)
public class ServletTest2 extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        ServletConfig servletConfig = getServletConfig();
        //获取初始配置信息即可
        //根据参数名获取参数值
        String keya = servletConfig.getInitParameter("key2a");
        System.out.println("key2a:" + keya);

        //获取所有初始参数的名字
        //hasMoreElements 判断有没有下一个参数，如果有返回true，如果没有返回false
        //nextElement     1.取出下一个元素 2.向下移动游标
        Enumeration<String> initParameterNames = servletConfig.getInitParameterNames();

        while (initParameterNames.hasMoreElements()) {
            String pName=initParameterNames.nextElement();
            System.out.println(pName+":"+getInitParameter(pName));
        }
        System.out.println("**********************************");
        //获取ServletContest()
        ServletContext servletContext1 = getServletContext();
        ServletContext servletContext2 = servletConfig.getServletContext();
        ServletContext servletContext3 = req.getServletContext();

        String encoding=servletContext1.getInitParameter("encoding");
        Enumeration<String> pNames=servletContext1.getInitParameterNames();
        while (pNames.hasMoreElements()) {
            String pName=pNames.nextElement();
            System.out.println(pName+":"+servletContext1.getInitParameter(pName));
        }

        //从域对象中读取数据
        String ka=(String) servletContext1.getAttribute("ka");
        System.out.println("ka:"+ka);
    }
}
